package Controleur;

import java.util.HashMap;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import Helpers.Configuration;
import Helpers.Helpers;
import Journalisation.Logging;
import Modele.Billet;
import Modele.Panier;


public class FrontController extends HttpServlet
{
	private static final long serialVersionUID = 1L;
	private static String LAYOUT = "/WEB-INF/view/layout/layout.jsp";
	
	private HashMap<String, CustomServlet> servlets = new HashMap<String, CustomServlet>();
	
	public void init(ServletConfig config) throws ServletException
	{
        super.init(config);
        
		try
		{			
			Configuration.TIMEOUT_BILLETS = Integer.parseInt(getServletContext().getInitParameter("timeoutBillets").toString());
			Configuration.MAX_BILLETS = Integer.parseInt(getServletContext().getInitParameter("maxBilletsPanier").toString());
			Configuration.MAX_REPRESENTATIONS_PAGE = Integer.parseInt(getServletContext().getInitParameter("maxRepresentationsPage").toString());
			Configuration.MAX_SPECTACLES_PAGE = Integer.parseInt(getServletContext().getInitParameter("maxSpectaclesPage").toString());
		}
		catch ( Exception e )
		{
		}
	}
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
	{
		processRequest ( request, response, false );
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
	{
		processRequest ( request, response, true );
	}
	
	private void processRequest ( HttpServletRequest request, HttpServletResponse response, boolean post )
	{
		CustomServlet servlet = null;
		try
		{
			executerActions ( request );
			
			String action = securiserNomAction ( request.getRequestURI().replaceFirst( request.getContextPath() + "/", "") );		
			servlet = getServlet ( action, request );
			request.setAttribute("layout", LAYOUT);	
			
			if ( servlet != null )
			{
				servlet.setServletContext(getServletContext());
				
				if ( post )
					servlet.executePost(request, response );	
				else
					servlet.executeGet(request, response);	
				
				if ( request.getAttribute("layout") != null )
				{
					if ( request.getAttribute ( "page" ) == null )
						request.setAttribute("page", action.toLowerCase() );
					
					RequestDispatcher dis= getServletContext().getRequestDispatcher((String)request.getAttribute("layout"));
					dis.forward( request , response );	
				}	
			}
			else
			{				
				redirect ( response, request.getContextPath() );
				Logging.Message(request.getRemoteAddr() + " : Redirection vers la racine du site...", Logging.Type.INFO);
			}
		}
		catch (Exception e )
		{
			String nomServlet = ( servlet == null ) ? "inconnu" : servlet.getClass().getName();
			Logging.Message(request.getRemoteAddr() + " : Erreur dans le servlet : " + nomServlet + "\r\n" + e.toString(), Logging.Type.ERROR);
			
			try
			{
				RequestDispatcher dis= getServletContext().getRequestDispatcher("/WEB-INF/view/erreur.jsp");
				dis.forward( request , response );	
			}
			catch ( Exception ex ){}
		}
	
	}
	
	private String securiserNomAction ( String nom )
	{
		return nom.replace("/", "").replace(".", "");
	}
	
	private void redirect ( HttpServletResponse response, String url )
	{
		response.setContentType("text/plain");
		response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
		response.setHeader("Location", url);
	}

	private CustomServlet getServlet ( String action, HttpServletRequest request )
	{
		CustomServlet servlet = null;
		
		try 
		{		
			if ( servlets.containsKey(action))
				servlet = servlets.get(action);
			else
			{
	            Class c = Class.forName("Controleur." + action + "Servlet" );      
	            servlet = (CustomServlet)c.newInstance();
	            servlets.put(action, servlet);	   
			}            
		}
		catch ( Exception e )
		{
			Logging.Message(request.getRemoteAddr() + " : Servlet introuvable : " + action, Logging.Type.ERROR);
		}
		
		return servlet;
	}
	
	
	private void executerActions ( HttpServletRequest request )
	{
		Panier panier = Helpers.getPanier(request.getSession());
		Helpers.verifierExpirationPanier(panier);
		
		Logging.Message(request.getRemoteAddr() + " : " + getFullURL(request), Logging.Type.INFO);
	}
	
	
	
	String getFullURL(HttpServletRequest request) {
		 StringBuffer url = request.getRequestURL();
		 if (request.getQueryString() != null) {
		  url.append('?');
		  url.append(request.getQueryString());
		 }
		 return url.toString();
		}
}
